<template>
  <div class="access-data-view">
    <!-- 搜索区域 -->
    <div class="search-section">
      <div class="search-item">
        <label>患者姓名：</label>
        <input type="text" class="search-input" placeholder="请输入" v-model="searchForm.patientName">
      </div>
      
      <div class="search-item">
        <label>随访方案：</label>
        <select class="search-select" v-model="searchForm.followPlan">
          <option value="高血压随访">高血压随访</option>
          <option value="糖尿病随访">糖尿病随访</option>
          <option value="冠心病随访">冠心病随访</option>
        </select>
      </div>
      
      <div class="search-item">
        <label>状态：</label>
        <select class="search-select" v-model="searchForm.status">
          <option value="">请选择</option>
          <option value="待随访">待随访</option>
          <option value="已随访">已随访</option>
          <option value="失访">失访</option>
        </select>
      </div>
      
      <button class="search-btn">查询</button>
      <button class="reset-btn">重置</button>
    </div>
    
    <!-- 标签页 -->
    <div class="tabs">
      <div class="tab" :class="{ active: activeTab === 'pending' }" @click="activeTab = 'pending'">待随访</div>
      <div class="tab" :class="{ active: activeTab === 'completed' }" @click="activeTab = 'completed'">已随访</div>
    </div>
    
    <!-- 数据表格 -->
    <div class="table-container">
      <table class="data-table">
        <tbody>
          <div class="table-container">
          <el-table :data="tableData" border style="width: 100%">
            <el-table-column type="index" label="序号" width="60" />
            <el-table-column prop="recordName" label="姓名" width="80" />
            <el-table-column prop="recordSex" label="性别" width="80">
                <template v-slot="scope">
                  <el-tag style="background-color: deepskyblue; color: #fff;" v-if="scope.row.recordSex == 1">男</el-tag>
                  <el-tag style="background-color: pink;color: #fff;" v-if="scope.row.recordSex == 2">女</el-tag>
                </template>
              </el-table-column>
            <el-table-column prop="recordAge" label="年龄" width="80"/>
            <el-table-column prop="recordPhone" label="联系电话" width="120"/>
            <el-table-column prop="diseaseType" label="慢病病种" />
            <el-table-column prop="followupTime" label="计划随访时间">
                <template v-slot="scope">
                  {{ moment(scope.row.followupTime).format('YYYY-MM-DD') }}
                </template>
              </el-table-column>
            <el-table-column prop="followupType" label="随访方案"/>
            <el-table-column label="操作" width="150" >
              <template #default="scope">
                <el-button type="primary" @click="openFollowup(scope.row)" link>随访</el-button>
                <el-button type="primary" @click="openLost(scope.row)" link>失访</el-button>
              </template>
            </el-table-column>
          </el-table>
          
          <!-- 列表分页 -->
          <!-- 分页控件 -->
            <div class="pagination-container">
              <el-pagination
                v-model:current-page="paging.PageIndex"
                v-model:page-size="paging.PageSize"
                :page-sizes="[3, 5, 7, 10]"
                layout="total, sizes, prev, pager, next, jumper"
                :total="paging.totalCount"
                @size-change="handleSizeChange"
                @current-change="handleCurrentChange"
                class="medical-pagination"
              />
            </div>
        </div>
        </tbody>
      </table>
    </div>
    
    <!-- 分页 -->
    <div class="pagination">
      <span class="total">总数: {{ totalCount }}条</span>
      <div class="page-controls">
        <button class="page-btn" :disabled="currentPage === 1">
          &lt;
        </button>
        <button 
          v-for="page in pageNumbers" 
          :key="page"
          class="page-btn" 
          :class="{ active: page === currentPage }"
          @click="currentPage = page"
        >
          {{ page }}
        </button>
        <button class="page-btn" :disabled="currentPage === totalPages">
          &gt;
        </button>
      </div>
      <div class="page-size">
        <select v-model="pageSize" @change="changePageSize">
          <option :value="10">10条/页</option>
          <option :value="15">15条/页</option>
          <option :value="20">20条/页</option>
        </select>
      </div>
      <div class="jump-to">
        <span>跳至</span>
        <input type="number" v-model="jumpPage" min="1" :max="totalPages" class="jump-input">
        <span>页</span>
      </div>
    </div>
    
    <!-- 随访弹窗 -->
    <el-dialog v-model="followupDialogVisible" title="高血压—一级管理随访记录表" width="50%" top="5vh" :close-on-click-modal="false" append-to-body>
      <div class="followup-form">
        <el-form :model="followupForm" label-width="120px" label-position="top">
          <el-row :gutter="12">
            <el-col :span="12">
              <el-form-item label="姓名">
                <el-input v-model="followupForm.name" placeholder="自动带入或填写" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="编号">
                <el-input v-model="followupForm.serial" placeholder="填写编号" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="随访日期">
                <el-date-picker v-model="followupForm.visitDate" type="date" value-format="YYYY-MM-DD" placeholder="选择日期" style="width:100%" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="随访方式">
                <el-radio-group v-model="followupForm.method">
                  <el-radio label="门诊" />
                  <el-radio label="家访" />
                  <el-radio label="电话" />
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>

          <el-divider content-position="left">症状</el-divider>
          <el-checkbox-group v-model="followupForm.symptoms" class="symptom-group">
            <el-checkbox label="无症状" />
            <el-checkbox label="有症状" />
            <el-checkbox label="头痛" />
            <el-checkbox label="头晕" />
            <el-checkbox label="心悸" />
            <el-checkbox label="胸闷" />
            <el-checkbox label="呼吸困难" />
            <el-checkbox label="鼻出血不止" />
          </el-checkbox-group>

          <el-divider content-position="left">体征</el-divider>
          <el-row :gutter="12">
            <el-col :span="8">
              <el-form-item label="血压(mmHg)">
                <el-input v-model="followupForm.bloodPressure" placeholder="例如 130/80" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="体重(kg)">
                <el-input v-model="followupForm.weight" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="体质指数(kg/m²)">
                <el-input v-model="followupForm.bmi" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="心率(次/分)">
                <el-input v-model="followupForm.heartRate" />
              </el-form-item>
            </el-col>
            <el-col :span="16">
              <el-form-item label="其他">
                <el-input v-model="followupForm.otherSigns" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-divider content-position="left">生活方式指导</el-divider>
          <el-row :gutter="12">
            <el-col :span="8">
              <el-form-item label="日吸烟量(支)">
                <el-input v-model="followupForm.smokePerDay" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="日饮酒量(两)">
                <el-input v-model="followupForm.drinkPerDay" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="运动(次/周)">
                <el-input v-model="followupForm.exerciseTimes" placeholder="次数/周" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="运动(分钟/次)">
                <el-input v-model="followupForm.exerciseMinutes" placeholder="分钟/次" />
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="摄盐量">
                <el-radio-group v-model="followupForm.salt">
                  <el-radio label="轻(≤6g)" />
                  <el-radio label="中(6-12g)" />
                  <el-radio label="重(>12g)" />
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="心理调整">
                <el-radio-group v-model="followupForm.psychology">
                  <el-radio label="良好" />
                  <el-radio label="一般" />
                  <el-radio label="差" />
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="遵医行为">
                <el-radio-group v-model="followupForm.compliance">
                  <el-radio label="良好" />
                  <el-radio label="一般" />
                  <el-radio label="差" />
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>

          <el-divider content-position="left">用药与不良反应</el-divider>
          <el-row :gutter="12">
            <el-col :span="8">
              <el-form-item label="服药依从性">
                <el-radio-group v-model="followupForm.medicineAdherence">
                  <el-radio label="规律" />
                  <el-radio label="间断" />
                  <el-radio label="不服药" />
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="药物不良反应">
                <el-radio-group v-model="followupForm.adverse">
                  <el-radio label="无" />
                  <el-radio label="有" />
                </el-radio-group>
              </el-form-item>
            </el-col>
            <el-col :span="8">
              <el-form-item label="低血压反应">
                <el-radio-group v-model="followupForm.hypotension">
                  <el-radio label="无" />
                  <el-radio label="偶尔" />
                  <el-radio label="频繁" />
                </el-radio-group>
              </el-form-item>
            </el-col>
          </el-row>

          <el-form-item label="此次随访分类">
            <el-radio-group v-model="followupForm.classification">
              <el-radio label="控制满意" />
              <el-radio label="控制不满意" />
              <el-radio label="不良反应" />
              <el-radio label="并发症" />
            </el-radio-group>
          </el-form-item>

          <el-divider content-position="left">用药情况</el-divider>
          <el-row :gutter="12">
            <el-col :span="12" v-for="(m, idx) in followupForm.medicines" :key="idx">
              <div class="medicine-line">
                <el-input v-model="m.name" placeholder="药物名称" style="width: 40%" />
                <span class="x-gap">每日</span>
                <el-input-number v-model="m.timesPerDay" :min="0" />
                <span class="x-gap">次 每次</span>
                <el-input-number v-model="m.countPerTime" :min="0" />
                <span class="x-gap">粒/片</span>
              </div>
            </el-col>
          </el-row>

          <el-divider content-position="left">转诊</el-divider>
          <el-row :gutter="12">
            <el-col :span="12">
              <el-form-item label="原因">
                <el-input v-model="followupForm.transferReason" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="机构及科别">
                <el-input v-model="followupForm.transferDept" />
              </el-form-item>
            </el-col>
          </el-row>

          <el-row :gutter="12">
            <el-col :span="12">
              <el-form-item label="下次随访时间">
                <el-date-picker v-model="followupForm.nextVisitDate" type="date" value-format="YYYY-MM-DD" placeholder="选择日期" style="width:100%" />
              </el-form-item>
            </el-col>
            <el-col :span="12">
              <el-form-item label="随访医生签名">
                <el-input v-model="followupForm.doctor" />
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="followupDialogVisible = false">清空</el-button>
          <el-button type="primary" @click="saveFollowup">保存</el-button>
        </div>
      </template>
    </el-dialog>

    <!-- 失访登记弹窗 -->
    <el-dialog v-model="lostDialogVisible" title="失访登记" width="720px" top="8vh" :close-on-click-modal="false" append-to-body>
      <div class="lost-wrapper">
        <div class="lost-card">
          <div class="avatar">
            <img src="D:\实训一\医疗慢病系统\Vue\healthcare-system-vue\src\images\u1676.png" alt="avatar">
          </div>
          <div class="info">
            <div class="name-line">
              <span class="name">{{ lostForm.name || '-' }}</span>
              <span class="sex-age">{{ lostForm.sex || '-' }}  {{ lostForm.age || '-' }}岁</span>
            </div>
            <div class="row">联系方式：<span class="primary">{{ lostForm.phone || '-' }}</span></div>
            <div class="row">身份证号：<span class="primary">{{ lostForm.idMasked || '-' }}</span></div>
          </div>
        </div>

        <el-form :model="lostForm" label-width="90px" label-position="left">
          <el-form-item label="失访原因">
            <el-select v-model="lostForm.reason" placeholder="请选择" style="width:100%">
              <el-option label="电话无人接听" value="电话无人接听" />
              <el-option label="电话空号/停机" value="电话空号/停机" />
              <el-option label="地址搬迁" value="地址搬迁" />
              <el-option label="外出不在" value="外出不在" />
              <el-option label="其他" value="其他" />
            </el-select>
          </el-form-item>
          <el-form-item label="备注">
            <el-input v-model="lostForm.remark" type="textarea" :rows="6" placeholder="填写备注" />
          </el-form-item>
        </el-form>
      </div>
      <template #footer>
        <div class="dialog-footer">
          <el-button @click="lostDialogVisible = false">取消</el-button>
          <el-button type="primary" @click="saveLost">保存</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, reactive,onMounted } from 'vue';
import moment from 'moment';
import { Read, Write } from '@/Http/Axios';
import { ElMessage } from 'element-plus';

// 搜索表单
const searchForm = reactive({
  patientName: '',
  followPlan: '高血压随访',
  status: ''
});

// 标签页状态
const activeTab = ref('pending');

// 分页相关
const currentPage = ref(1);
const pageSize = ref(15);
const totalCount = ref(30);
const jumpPage = ref(1);

// 模拟患者数据
const tableData:any = ref([])

const querymodel = reactive({
  RecordName:""
})

const paging = reactive({
    PageIndex:1,
    PageSize:16,
    totalCount:0,
    totalPage:0
})

const getChronicData = () => {
  Read.get("http://localhost:5108/api/Manager/FollowupManagementShow",{params:{
    RecordName:querymodel.RecordName,
    PageIndex:paging.PageIndex,
    PageSize:paging.PageSize
  }})
  .then(res=>{
    tableData.value = res.data.data.data
    paging.totalCount = res.data.totalCount
    paging.totalPage = res.data.totalPage
  })
}

onMounted(()=>{
  getChronicData()
})

const handleSizeChange = (val: number) => {
  console.log(`${val} items per page`)
  paging.PageSize = val;
  getChronicData()
}
const handleCurrentChange = (val: number) => {
  console.log(`current page: ${val}`)
  paging.PageIndex = val;
  getChronicData()
}

// 总页数
const totalPages = computed(() => {
  return Math.ceil(totalCount.value / pageSize.value);
});

// 页码数组
const pageNumbers = computed(() => {
  const pages = [];
  const maxVisible = 5;
  let startPage = Math.max(1, currentPage.value - Math.floor(maxVisible / 2));
  let endPage = Math.min(totalPages.value, startPage + maxVisible - 1);
  
  if (endPage - startPage + 1 < maxVisible) {
    startPage = Math.max(1, endPage - maxVisible + 1);
  }
  
  for (let i = startPage; i <= endPage; i++) {
    pages.push(i);
  }
  return pages;
});

// 改变每页显示数量
const changePageSize = () => {
  currentPage.value = 1;
  jumpPage.value = 1;
};

// 随访弹窗与表单
const followupDialogVisible = ref(false)
const followupForm = reactive({
  name: '',
  serial: '',
  visitDate: moment().format('YYYY-MM-DD'),
  method: '门诊',
  symptoms: [] as string[],
  bloodPressure: '',
  weight: '',
  bmi: '',
  heartRate: '',
  otherSigns: '',
  smokePerDay: '',
  drinkPerDay: '',
  exerciseTimes: '',
  exerciseMinutes: '',
  salt: '轻(≤6g)',
  psychology: '良好',
  compliance: '良好',
  medicineAdherence: '规律',
  adverse: '无',
  hypotension: '无',
  classification: '控制满意',
  medicines: [
    { name: '', timesPerDay: 0, countPerTime: 0 },
    { name: '', timesPerDay: 0, countPerTime: 0 },
    { name: '', timesPerDay: 0, countPerTime: 0 }
  ],
  transferReason: '',
  transferDept: '',
  nextVisitDate: '',
  doctor: ''
})

const openFollowup = (row: any) => {
  followupForm.name = row.recordName || row.RecordName || row.recordname || ''
  followupForm.visitDate = moment(row.followupTime).isValid() ? moment(row.followupTime).format('YYYY-MM-DD') : moment().format('YYYY-MM-DD')
  followupDialogVisible.value = true
}

const saveFollowup = () => {
  const payload = { ...followupForm }
  Write.post('/Followup/Save', payload)
    .then(()=>{
      ElMessage.success('随访记录已保存')
      followupDialogVisible.value = false
      getChronicData()
    })
    .catch(()=>{
      ElMessage.error('保存失败，请稍后重试')
    })
}

// 失访弹窗
const lostDialogVisible = ref(false)
const lostForm = reactive({
  name: '',
  sex: '',
  age: '',
  phone: '',
  idMasked: '',
  reason: '',
  remark: ''
})

const maskId = (id: string) => {
  if (!id) return ''
  if (id.length < 8) return id
  return id.substring(0,4) + '******' + id.substring(id.length-4)
}

const openLost = (row: any) => {
  lostForm.name = row.recordName || row.RecordName || ''
  lostForm.sex = row.recordSex == 1 ? '男' : (row.recordSex == 2 ? '女' : '')
  lostForm.age = row.recordAge || ''
  lostForm.phone = row.recordPhone || ''
  lostForm.idMasked = row.recordIdcard || ''
  lostForm.reason = ''
  lostForm.remark = ''
  lostDialogVisible.value = true
}

const saveLost = () => {
  const payload = { ...lostForm }
  Write.post('/Followup/LostSave', payload)
    .then(()=>{
      ElMessage.success('失访登记已保存')
      lostDialogVisible.value = false
      getChronicData()
    })
    .catch(()=>{
      ElMessage.error('保存失败，请稍后重试')
    })
}
</script>

<style scoped>
.access-data-view {
  padding: 20px;
  background-color: #f5f7fa;
  min-height: 100vh;
}

/* 搜索区域样式 */
.search-section {
  background-color: #fff;
  padding: 20px;
  border-radius: 4px;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  margin-bottom: 20px;
  display: flex;
  align-items: center;
  gap: 20px;
}

.search-item {
  display: flex;
  align-items: center;
  gap: 8px;
}

.search-item label {
  font-size: 14px;
  color: #666;
}

.search-input,
.search-select {
  padding: 6px 12px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.search-input {
  width: 150px;
}

.search-select {
  width: 150px;
}

.search-btn,
.reset-btn {
  padding: 6px 16px;
  border: none;
  border-radius: 4px;
  font-size: 14px;
  cursor: pointer;
}

.search-btn {
  background-color: #409eff;
  color: #fff;
}

.reset-btn {
  background-color: #f0f2f5;
  color: #606266;
  margin-left: 10px;
}

/* 标签页样式 */
.tabs {
  display: flex;
  background-color: #fff;
  border-bottom: 1px solid #ebeef5;
  margin-bottom: 0;
}

.tab {
  padding: 12px 30px;
  cursor: pointer;
  font-size: 14px;
  color: #606266;
  border-bottom: 2px solid transparent;
}

.tab.active {
  color: #409eff;
  border-bottom-color: #409eff;
}

/* 表格样式 */
.table-container {
  background-color: #fff;
  border: 1px solid #ebeef5;
  border-top: none;
  overflow: hidden;
}

.data-table {
  width: 100%;
  border-collapse: collapse;
}

.data-table th,
.data-table td {
  padding: 12px;
  text-align: left;
  border-bottom: 1px solid #ebeef5;
  font-size: 14px;
}

.data-table th {
  background-color: #f5f7fa;
  font-weight: 500;
  color: #606266;
}

.disease-tag {
  background-color: #ecf5ff;
  color: #409eff;
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 12px;
}

.follow-btn,
.miss-btn {
  padding: 4px 8px;
  border: none;
  border-radius: 4px;
  font-size: 12px;
  cursor: pointer;
  margin-right: 5px;
}

.follow-btn {
  background-color: #409eff;
  color: #fff;
}

.miss-btn {
  background-color: #f56c6c;
  color: #fff;
}

/* 分页样式 */
.pagination {
  background-color: #fff;
  padding: 15px 20px;
  border: 1px solid #ebeef5;
  border-top: none;
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.total {
  font-size: 14px;
  color: #606266;
}

.page-controls {
  display: flex;
  align-items: center;
  gap: 5px;
}

.page-btn {
  padding: 4px 10px;
  border: 1px solid #ddd;
  background-color: #fff;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.page-btn.active {
  background-color: #409eff;
  color: #fff;
  border-color: #409eff;
}

.page-btn:disabled {
  cursor: not-allowed;
  opacity: 0.5;
}

.page-size select,
.jump-input {
  padding: 4px 8px;
  border: 1px solid #ddd;
  border-radius: 4px;
  font-size: 14px;
}

.jump-to {
  display: flex;
  align-items: center;
  gap: 8px;
  font-size: 14px;
  color: #606266;
}

.jump-input {
  width: 50px;
  text-align: center;
}

/* 随访弹窗表单样式 */
.followup-form {
  max-height: 70vh;
  overflow: auto;
  padding-right: 4px;
}
.followup-form :deep(.el-form-item) {
  margin-bottom: 14px;
}
.followup-form :deep(.el-row) {
  display: block;
}
.followup-form :deep(.el-col) {
  width: 100% !important;
}
.symptom-group {
  display: flex;
  flex-wrap: wrap;
  gap: 12px;
}
.medicine-line {
  display: flex;
  align-items: center;
  gap: 8px;
  margin-bottom: 8px;
}
.x-gap { color:#606266; }

/* 失访登记样式 */
.lost-wrapper { padding: 4px 4px 0; }
.lost-card {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 16px;
  background: #f6f8fb;
  border-radius: 6px;
  margin-bottom: 18px;
}
.lost-card .avatar img { width:64px; height:64px; border-radius: 50%; }
.lost-card .info { color:#606266; }
.lost-card .name-line { display:flex; align-items:center; gap:12px; margin-bottom:6px; }
.lost-card .name { font-size:16px; color:#303133; font-weight:600; }
.lost-card .sex-age { color:#909399; }
.lost-card .row { line-height: 24px; }
.primary { color:#409eff; }
</style>